package com.situ.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.pojo.Product;
import com.situ.mall.service.IProductService;
import com.situ.mall.util.JSONResult;
import com.situ.mall.util.LayUITableResult;
import com.situ.mall.util.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {
    private Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LayUITableResult selectByPage(Integer page, Integer limit) {
        // 记录开始时间
        // long begin = System.currentTimeMillis();

        PageHelper.startPage(page, limit);
        List<Product> list = productMapper.selectByPage();
        //用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        long total = pageInfo.getTotal();

        // 模拟service层耗时操作
        /*try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 记录结束时间
        long end = System.currentTimeMillis();
        long takeTime = end - begin;
        if (takeTime > 3000) {
            logger.error("=====执行结束，耗时 {} 毫秒======", takeTime);
        } else if (takeTime > 2000) {
            logger.warn("=====执行结束，耗时 {} 毫秒======", takeTime);
        } else {
            logger.info("=====执行结束，耗时 {} 毫秒======", takeTime);
        }*/

        return LayUITableResult.ok(list, total);
    }

    /*@Override
    public LayUITableResult selectByPage(Integer page, Integer limit) {
        int offset = (page - 1) * limit;
        List<Product> list = productMapper.selectByPage(offset, limit);
        int count = productMapper.selectTotalCount();

        return LayUITableResult.ok(list, (long)count);
    }*/

    @Override
    public JSONResult insert(Product product) {
        productMapper.insert(product);
        // 将上传的图片保存到Redis中
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE_TO_DB, product.getMainImage());
        System.out.println("上传图片到数据库：" + product.getMainImage());
        return JSONResult.ok("插入成功");
    }
}
